package dao.daoImpl;

import common.DataSourceUtils;
import dao.UserMapper;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import pojo.User;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by Administrator on 2017-12-10.
 */
public class UserMapperImpl implements UserMapper {

    @Override
    public List<User> getAllUser() throws SQLException {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        String sql="select * from user";
        return qr.query(sql,new BeanListHandler<User>(User.class));
    }

    @Override
    public List<User> getCurrUser(int pageNow, int page_size) throws SQLException {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        String sql="select * from user limit ?,?";
        return qr.query(sql,new BeanListHandler<User>(User.class),(pageNow-1)*page_size,page_size);
    }

    @Override
    public int deleteUser(int id) throws SQLException {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        String sql="delete from user where id=?";
        return qr.update(sql,id);
    }

    @Override
    public User selectUser(int id) throws SQLException {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        String sql="select * from user where id=?";
        return qr.query(sql,new BeanHandler<User>(User.class),id);
    }

    @Override
    public int updateUserInfo(User user) throws SQLException {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        String sql="update user set sex = ? , department=?,roleName=?,roleId=?,realName=?,tl=? where id=?";
        return qr.update(sql,user.getSex(),user.getDepartment(),user.getRoleName(),user.getRoleId(),user.getRealName(),user.getTl(),user.getId());
    }

    @Override
    public int creatUserInfo(User user) throws SQLException {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        String sql="insert into user (username,password,sex,tl,realName,department,roleId,roleName) values (?,?,?,?,?,?,?,?) ";
        return qr.update(sql,user.getUsername(),user.getPassword(),user.getSex(),user.getTl(),user.getRealName(),user.getDepartment(),user.getRoleId(),user.getRoleName());
    }

    @Override
    public User checkName(String username) throws SQLException {
        QueryRunner qr=new QueryRunner(DataSourceUtils.getDataSource());
        String sql="select * from user where username=?";
        return qr.query(sql,new BeanHandler<User>(User.class),username);
    }

}
